package com.fsd.admin.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;
import com.fsd.admin.dao.E_MenuDao;
import com.fsd.admin.entity.A_LoginInfo;
import com.fsd.admin.model.A_Employee;
import com.fsd.admin.model.E_Menu;
import com.fsd.admin.model.E_wechat;
import com.fsd.admin.service.E_MenuService;
import com.fsd.admin.service.E_WechatService;
import com.fsd.core.bean.Tree;
import com.fsd.core.common.BusinessException;
import com.fsd.core.util.Config;
import com.fsd.core.util.ParametersUtil;
import com.fsd.core.wechat.entity.menu.Button;
import com.fsd.core.wechat.entity.menu.Menu;
import com.fsd.core.wechat.util.WeixinUtil;
import com.google.gson.Gson;

/**
 * 微信菜单Service-实现类
 * @author Administrator
 *
 */

@Service("e_menuServiceImpl")
public class E_MenuServiceImpl extends MainServiceImpl<E_Menu, String> implements E_MenuService {

	private static final Logger log = Logger.getLogger(E_MenuServiceImpl.class);
    private String depict = "微信菜单";
    
    @Resource(name = "e_wechatServiceImpl")
	private E_WechatService wechatService;
    
    @Resource(name = "e_menuDaoImpl")
	public void setBaseDao(E_MenuDao e_menuDao) {
		super.setBaseDao(e_menuDao);
	}
	
	@Resource(name = "e_menuDaoImpl")
	private E_MenuDao objectDao;
	
	private String checkLeaf(String fid){
		long num = objectDao.getCount("parentid = '"+ fid +"'");
		if (num > 0)
			return "false";
		return "true";
	}
	
	private List<E_Menu> queryObjectListById(String fid){
		return objectDao.queryByHql("from E_Menu a where a.parentid = '"+ fid +"' order by sort asc");
	}
	
	/**
	 * 加载分页数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public ParametersUtil getObjectPageList(ParametersUtil param, A_Employee employee) throws Exception{
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("companyid", employee.getCompanyid()));
		c.addOrder(Order.asc("sort"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			c.add(Restrictions.eq("parentid", objectMap.get("fid")));
			if(objectMap.get("name") != null && !"".equals(objectMap.get("name"))){
				c.add(Restrictions.like("name", "%" + objectMap.get("name") + "%"));
			}
		}
		return objectDao.findPager(param , c);
	}
	
	/**
	 * 异步加载对象树
	 * @return
	 * @throws Exception
	 */
	public List<Tree> getAsyncObjectTree(String fid, A_Employee employee) throws Exception{
		List<E_Menu> list = this.queryObjectListById(fid);
		List<Tree> treelist = new ArrayList<Tree>();
		if (list != null && list.size() > 0){
			Tree tree = null;
			E_Menu obj = null;
			for (Object o : list) {
				obj = (E_Menu)o;
				tree = new Tree();
				tree.setId(obj.getId());
				tree.setText(obj.getName()+ "（" + obj.getTypename() + "-" + obj.getCode() + "）");
				tree.setLeaf(Boolean.valueOf(obj.getLeafed()));
				treelist.add(tree);
			}
		}
		return treelist;
	}

	/**
	 * 一次性加载部门树，根据权限加载
	 * @return
	 * @throws Exception
	 */
	public List<Tree> getAllObjectTree(ParametersUtil param, A_LoginInfo login) throws Exception{
		List<Tree> treelist = new ArrayList<Tree>();
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("wxid") != null && !"".equals(objectMap.get("wxid"))){
				List<E_Menu> list = this.queryObjectListById(objectMap.get("wxid").toString());
				treelist.addAll(this.getObjectTree(objectMap.get("wxid").toString(), list));
			}
		}
		return treelist;
	}
	private List<Tree> getObjectTree(String fid, List<E_Menu> list) throws Exception{
		List<Tree> treelist = new ArrayList<Tree>();
		if (list == null || list.size() == 0)
			return treelist;
		Tree node = null;
		List<E_Menu> objList = null;
		for (E_Menu obj : list) {
			if (obj.getParentid().equals(fid)){
				node = new Tree();
				node.setId(obj.getId());
				node.setText(obj.getName());
				node.setLeaf(Boolean.valueOf(obj.getLeafed()));
				if(!node.isLeaf()){
					objList = this.queryObjectListById(obj.getId());
					node.setChildren(this.getObjectTree(obj.getId(), objList));
					node.setExpanded(true);
				}
				treelist.add(node);
			}
		}
		return treelist;
	}
	
	/**
	 * 保存对象（添加、修改）
	 * @param obj
	 */
	public void saveObject(E_Menu obj, A_Employee employee) throws Exception{
		if(obj.getId() != null && !"".equals(obj.getId())){
			//修改
			E_Menu obj_old = objectDao.get(obj.getId());
			obj_old.setParentid(obj.getParentid());
			obj_old.setParentname(obj.getParentname());
			obj_old.setCode(obj.getCode());
			obj_old.setType(obj.getType());
			obj_old.setTypename(obj.getTypename());
			obj_old.setName(obj.getName());
			obj_old.setSort(obj.getSort());
			obj_old.setAurl(obj.getAurl());
			obj_old.setRemark(obj.getRemark());
			obj_old.setUpdatedate(this.getData());//设置修改日期
			obj_old.setUpdateemployeeid(employee.getId());//设置修改用户id
			obj_old.setUpdateemployeename(employee.getRealname());//设置修改用户姓名
			objectDao.update(obj_old);
		}else{
			//添加
			obj.setId(this.getUUID());//设置主键
			obj.setCompanyid(employee.getCompanyid());//所属单位
			obj.setAdddate(this.getData());//设置添加日期
			obj.setAddemployeeid(employee.getId());//设置添加用户id
			obj.setAddemployeename(employee.getRealname());//设置添加用户姓名
			obj.setLeafed("true");;
			objectDao.save(obj);
			objectDao.executeHql("update E_Menu t set t.leafed = 'false' where t.id = '" + obj.getParentid() + "'");
		}
		this.sysLogService.saveObject(Config.LOGTYPEBC, this.depict + obj.getId() + obj.getName(), employee, E_MenuServiceImpl.class);
	}
	
	/**
	 * 根据ID加载对象
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	public E_Menu getObjectById(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("id") == null && "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}
		E_Menu obj = objectDao.get(objectMap.get("id").toString());
		if(obj == null){
			throw new BusinessException(depict + "数据不存在!");
		}
		return obj;
	}
	
	/**
	 * 删除对象
	 * @param parameters
	 */
	public void delObject(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String ids = this.getSQLinByIDList(dir);
		String oid = dir.get(0);
		objectDao.executeHql("delete from E_Menu t where t.id in (" + ids + ")");
		E_Menu obj = objectDao.get(oid);
		if (obj != null){
			objectDao.executeHql("update E_Menu t set t.leafed = '" + this.checkLeaf(obj.getParentid()) + "' where t.id = '" + obj.getParentid() + "'");
		}
	}
	
	/**
	 * 顺序排序
	 * @param parameters
	 */
	public void updateSortObject(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		List<String> idList = (List<String>) objectMap.get("ids");
		String ids = this.getSQLinByIDList(idList);
		E_Menu objDW = objectDao.get(objectMap.get("id").toString());
		if (objDW == null)
			throw new BusinessException(depict + "获取定位对象为空!");
		List<E_Menu> objList = objectDao.queryByHql("from E_Menu t where " +
				"t.parentid = '" + objDW.getParentid() + "' " +
				"and t.id not in (" + ids + ") " +
				"and t.sort >= " + objDW.getSort() + " order by t.sort asc");
		long sort = objDW.getSort();
		for (String id : idList) {
			objectDao.executeHql("update E_Menu t set t.sort = " + sort + " where t.id = '" + id + "'");
			sort++;
		}
		for (E_Menu obj : objList) {
			objectDao.executeHql("update E_Menu t set t.sort = " + sort + " where t.id = '" + obj.getId() + "'");
			sort++;
		}
	}
	
	/**
	 * 获取微信平台菜单
	 * @param param
	 * @return
	 */
	public List<Tree> getWeChatMenu(ParametersUtil param) throws Exception{
		List<Tree> menulist = new ArrayList<Tree>();
		String wxid = "";
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			wxid = objectMap.get("wxid").toString();
		}
		if (wxid == null || wxid.equals(""))
			throw new BusinessException("获取 '微信平台菜单' 失败，微信号不能为空!");
		E_wechat wechat = wechatService.getWeChatCheckInfo(wxid);
		Menu menu = WeixinUtil.queryMenu(wechat.getAppid(), wechat.getAppsecret());
		Tree tree = null;
		Tree tree1 = null;
		Button button = null;
		Button buttonsub = null;
		if (menu.getButton() != null && menu.getButton().length > 0){
			for (int i = 0; i < menu.getButton().length; i++) {
				button = (Button)menu.getButton()[i];
				tree = new Tree();
				tree.setId("1" + String.valueOf(i));
				if (button.getSub_button() != null && button.getSub_button().length > 0){
					tree.setText(button.getName());
					tree.setLeaf(false);
					for (int j = 0; j < button.getSub_button().length; j++) {
						buttonsub = (Button)button.getSub_button()[j];
						tree1 = new Tree();
						tree1.setId("2" + String.valueOf(i) + String.valueOf(j));
						tree1.setLeaf(true);
						if (buttonsub.getType().equals("view")){
							tree1.setText(buttonsub.getName() + "（" + buttonsub.getType() + "-" + buttonsub.getUrl() + "）");
						}else{
							tree1.setText(buttonsub.getName() + "（" + buttonsub.getType() + "-" + buttonsub.getKey() + "）");
						}
						tree.getChildren().add(tree1);
					}
				}else{
					if (button.getType().equals("view")){
						tree.setText(button.getName() + "（" + button.getType() + "-" + button.getUrl() + "）");
					}else{
						tree.setText(button.getName() + "（" + button.getType() + "-" + button.getKey() + "）");
					}
					tree.setLeaf(true);
				}
				menulist.add(tree);
			}
		}
		return menulist;
	}
	
	private Button getButtonByObject (E_Menu obj, int wordNum){
		Button button = new Button();
		button.setKey(obj.getCode());
		button.setName(obj.getName());
		if (button.getName().length() > wordNum){
			button.setName(button.getName().substring(0, wordNum));
		}
		if (obj.getType().equals("e_wxcdlj")){
			button.setType("view");
			button.setUrl(obj.getAurl());
		}else{
			button.setType("click");
		}
		return button;
	}
	
	/**
	 * 菜单组创建
	 * @param menu
	 * @param menuList
	 */
	private Button[] getObjectStruct(String parentID, List<E_Menu> menuList){
		E_Menu obj = null;
		List<Button> buttonList = new ArrayList<Button>();
		for (int i = 0; i < menuList.size(); i++) {
			if (buttonList.size() >= 5)
				break;
			obj = menuList.get(i);
			if(parentID.equals(obj.getParentid())){
				buttonList.add(this.getButtonByObject(obj, 13));
			}
		}
		return (Button[])buttonList.toArray(new Button[0]);
	}
	
	/**
	 * 同步微信平台菜单
	 * @param param
	 * @return
	 */
	public void synchroUserMenu(ParametersUtil param) throws Exception{
		String wxid = "";
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			wxid = objectMap.get("wxid").toString();
		}
		if (wxid == null || wxid.equals(""))
			throw new BusinessException("获取 '微信平台菜单' 失败，微信号不能为空!");
		E_wechat wechat = wechatService.getWeChatCheckInfo(wxid);
		List<E_Menu> menuList = objectDao.queryByHql("from E_Menu a where a.wechatid = '"+ wxid +"' order by sort asc");
		Menu menu = new Menu();
		List<Button> buttonList = new ArrayList<Button>();
		E_Menu obj = null;
		Button button = null;
		for (int i = 0; i < menuList.size(); i++) {
			if (buttonList.size() >= 3)
				break;
			obj = menuList.get(i);
			if(wxid.equals(obj.getParentid())){
				button = this.getButtonByObject(obj, 4);
				if (obj.getLeafed().equals("false")){
					button.setSub_button(this.getObjectStruct(obj.getId(), menuList));
				}
				buttonList.add(button);
			}
		}
		menu.setButton((Button[])buttonList.toArray(new Button[0]));
		WeixinUtil.createMenu(menu, wechat.getAppid(), wechat.getAppsecret());
	}
}
